<template>
  <Card class="menu-tree-page"
        dis-hover>
    <p slot="title">角色管理</p>
    <div class="tree-box">
      <Tree ref="tree"
            :data="treeData"
            show-checkbox
            :empty-text="emptyText"
            @on-check-change="checkedIds"></Tree>
    </div>
    <div class="button-group">
      <Button type="primary"
              style="margin-right: 10px;"
              @click="handleSubmit">提交</Button>
      <Button type="primary"
              @click="goBack">返回</Button>
    </div>
  </Card>
</template>

<script>
import { getSystemMenuList } from '@/api/data'
import { editRoleSysUserMenu } from '@/api/handle'

export default {
  name: 'menu-tree',
  data () {
    return {
      treeData: [],
      emptyText: '暂无数据',
      selectedIds: []
    }
  },
  mounted () {
    this.getMenuLists()
  },
  methods: {
    getMenuLists () {
      const UserType = this.$route.query.Id // 角色ID
      getSystemMenuList({ UserType }).then(res => {
        if (res.data.success) {
          this.treeData = eval(res.data.data)
        }
      })
    },
    checkedIds (ids) {
      this.selectedIds = ids
    },
    handleSubmit () {
      if (this.$route.query.Id) {
        this.selectedIds = this.$refs.tree.getCheckedNodes()
        let listMenus = this.selectedIds.map(item => item.MenuId)
        let ListMenu = []
        for (let [index, val] of listMenus.entries()) {
          ListMenu.push({ 'Key': 'MenuId' + index, 'Value': val })
        }
        const requestData = {
          SysUserId: localStorage.getItem('userId'),
          UserType: this.$route.query.Id,
          ListMenu
        }
        editRoleSysUserMenu(requestData).then(res => {
          if (res.data.success) this.$Message.success('编辑成功')
          else this.$Message.info(res.data.msg)
        })
      } else {
        this.$Message.info('缺少参数，请到角色管理页面，点击“授权”按钮进行操作！')
      }
    },
    goBack () {
      // this.$router.go(-1)
      this.$router.push({
        name: 'role_manage'
      })
    }
  }
}
</script>

<style lang="less" scoped>
.menu-tree-page {
  height: 85vh;
  .button-group {
    margin-top: 20px;
    text-align: center;
  }
}
</style>
